﻿using System;
using System.Web;
using System.Data;
using AliCMS.SystemModule;
using System.Collections.Generic;

namespace AliCMS.Lib
{
    public class MultiUserAdminPageBase_Old : AdminPageBase
    {
        public MultiUserAdminPageBase_Old(string pathInTemplate)
            : base(pathInTemplate)
        {
        }

        protected void SetDefaultSubInstance(string instanceID, string id, string innerID)
        {
            Dictionary<string, string> kvs = new Dictionary<string, string>();
            kvs["DefaultSubInstanceIDOf" + instanceID] = id;
            kvs["DefaultSubInstanceInnerIDOf" + instanceID] = innerID;
            Manager.AddToUser(kvs);
        }

        private DataTable getSubInstances(int instanceID, Dictionary<string, string> user, bool hasSubUser)
        {
            DataTable result = new DataTable();
            result.Columns.Add("ID", typeof(Guid));
            result.Columns.Add("InnerID", typeof(int));
            result.Columns.Add("Name", typeof(string));
            result.Columns.Add("UserID", typeof(Guid));

            using (IObject bll = Manager.CreateObject("SubInstance", instanceID, ContentLang, false))
            {
                DataRow instance = Manager.Instances.Select(Alias.Instance.InnerID + "=" + instanceID)[0];
                DataRow[] rows = Manager.Objects.Select(Alias.Module.Object.Namespace + "='" + instance[Alias.Module.Namespace] + "' and " + Alias.Module.Object.Name + "='SubInstance'");
                if (rows.Length == 0)
                    return result;

                string userIDField = Manager.Properties.Select(Alias.Module.Object.Property.ObjectID + "='" + rows[0][Alias.Module.Object.ID] + "' and " + Alias.Module.Object.Property.Name + "='UserID'")[0][Alias.Module.Object.Property.UniqueInnerID].ToString();

                string condition = userIDField + "=" + user["ID"];
                string[] subusers = null;
                if (hasSubUser)
                {
                    subusers = user["SubUser"].Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string subuser in subusers)
                    {
                        condition = " OR " + userIDField + "=" + subuser.Split('|')[0];
                    }
                }

                DataTable table = (DataTable)bll.GetType().InvokeMember("List", System.Reflection.BindingFlags.InvokeMethod, null, bll, new object[] { -1, -1, condition, null });
                if (table.Rows.Count == 0)
                    return result;

                string idField = Manager.Properties.Select(Alias.Module.Object.Property.ObjectID + "='" + rows[0][Alias.Module.Object.ID] + "' and " + Alias.Module.Object.Property.Name + "='ID'")[0][Alias.Module.Object.Property.UniqueInnerID].ToString();
                string innerIDField = Manager.Properties.Select(Alias.Module.Object.Property.ObjectID + "='" + rows[0][Alias.Module.Object.ID] + "' and " + Alias.Module.Object.Property.Name + "='InnerID'")[0][Alias.Module.Object.Property.UniqueInnerID].ToString();
                string nameField = Manager.Properties.Select(Alias.Module.Object.Property.ObjectID + "='" + rows[0][Alias.Module.Object.ID] + "' and " + Alias.Module.Object.Property.Name + "='Name'")[0][Alias.Module.Object.Property.UniqueInnerID].ToString();

                IObject privilegeBll = null;
                string roleNoField = null;
                string subInstanceIDField = null;

                foreach (DataRow subinstance in table.Rows)
                {
                    bool add = true;

                    #region 如果子用户，检查是否有权限。如果有任意权限，则采纳
                    if (hasSubUser && subinstance[userIDField].ToString() != user["ID"])
                    {
                        if (privilegeBll == null)
                        {
                            DataRow userInstance = Manager.Instances.Select(Alias.Module.Namespace + "='AliCMS.UserModule'")[0];
                            privilegeBll = Manager.CreateObject("Privilege", (int)userInstance[Alias.Instance.InnerID], PageLang, false);

                            rows = Manager.Objects.Select(Alias.Module.Object.Namespace + "='AliCMS.UserModule' and " + Alias.Module.Object.Name + "='Privilege'");
                            roleNoField = Manager.Properties.Select(Alias.Module.Object.Property.ObjectID + "='" + rows[0][Alias.Module.Object.ID] + "' and " + Alias.Module.Object.Property.Name + "='RoleNo'")[0][Alias.Module.Object.Property.UniqueInnerID].ToString();
                            subInstanceIDField = Manager.Properties.Select(Alias.Module.Object.Property.ObjectID + "='" + rows[0][Alias.Module.Object.ID] + "' and " + Alias.Module.Object.Property.Name + "='SubInstanceID'")[0][Alias.Module.Object.Property.UniqueInnerID].ToString();
                        }

                        condition = null;
                        foreach (string subuser in subusers)
                        {
                            string[] pair = subuser.Split(',');
                            if (subinstance[userIDField].ToString() != pair[0])
                                continue;

                            if (condition != null)
                                condition += " OR ";
                            condition += "(" + roleNoField + "=" + pair[1] + " AND " + subInstanceIDField + "=" + subinstance[idField] + ")";
                        }

                        DataTable privilegeTable = (DataTable)bll.GetType().InvokeMember("List", System.Reflection.BindingFlags.InvokeMethod, null, bll, new object[] { -1, -1, condition, null });
                        if (privilegeTable.Rows.Count == 0)
                            add = false;
                    }
                    #endregion

                    if (add)
                    {
                        DataRow row = result.NewRow();
                        row["ID"] = subinstance[idField];
                        row["InnerID"] = subinstance[innerIDField];
                        row["Name"] = subinstance[nameField];
                        row["UserID"] = subinstance[userIDField];
                        result.Rows.Add(row);
                    }
                }

                if (privilegeBll != null)
                    privilegeBll.Dispose();
            }

            return result;
        }

        #region Properties
        protected DataTable SubInstances
        {
            get
            {
                string defaultSubInstanceInnerIDOf = null;
                string[] subInstances = null;

                #region 如果User数据中中没有子实例信息，则写入
                Dictionary<string, string> user = Manager.User;
                if (!user.ContainsKey("DefaultSubInstanceIDOf" + InstanceID))
                {
                    DataTable subinstances = getSubInstances(InstanceID, user, true);

                    Dictionary<string, string> kvs = new Dictionary<string, string>();
                    string subinstancesof = String.Empty;
                    foreach (DataRow subinstance in subinstances.Rows)
                    {
                        if (subinstancesof == String.Empty)
                        {
                            defaultSubInstanceInnerIDOf = subinstance["InnerID"].ToString();
                            kvs["DefaultSubInstanceIDOf" + InstanceID] = subinstance["ID"].ToString();
                            kvs["DefaultSubInstanceInnerIDOf" + InstanceID] = subinstance["InnerID"].ToString();
                        }
                        else
                        {
                            subinstancesof += ";";
                        }
                        subinstancesof += subinstance["ID"] + "|" + subinstance["InnerID"] + "|" + subinstance["Name"] + "|" + subinstance["UserID"];
                    }
                    kvs["SubInstancesOf" + InstanceID] = subinstancesof;
                    Manager.AddToUser(kvs);

                    subInstances = subinstancesof.Split(';');

                    /*
                    using (IObject bll = Manager.CreateObject("SubInstance", InstanceID, ContentLang, false))
                    {
                        DataRow instance = Manager.Instances.Select(Alias.Instance.InnerID + "=" + InstanceID)[0];
                        DataRow[] rows = Manager.Objects.Select(Alias.Module.Object.Namespace + "='" + instance[Alias.Module.Namespace] + "' and " + Alias.Module.Object.Name + "='SubInstance'");
                        if (rows.Length == 0)
                            Response.Redirect(BuildUrl(null, "login", null));

                        string userIDField = Manager.Properties.Select(Alias.Module.Object.Property.ObjectID + "='" + rows[0][Alias.Module.Object.ID] + "' and " + Alias.Module.Object.Property.Name + "='UserID'")[0][Alias.Module.Object.Property.UniqueInnerID].ToString();

                        string condition = userIDField + "=" + user["ID"];
                        string[] subusers = user["SubUser"].Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string subuser in subusers)
                        {
                            condition = " OR " + userIDField + "=" + subuser.Split('|')[0];
                        }

                        DataTable table = (DataTable)bll.GetType().InvokeMember("List", System.Reflection.BindingFlags.InvokeMethod, null, bll, new object[] { -1, -1, condition, null });
                        if (table.Rows.Count == 0)
                            Response.Redirect(BuildUrl(null, "login", null));

                        string idField = Manager.Properties.Select(Alias.Module.Object.Property.ObjectID + "='" + rows[0][Alias.Module.Object.ID] + "' and " + Alias.Module.Object.Property.Name + "='ID'")[0][Alias.Module.Object.Property.UniqueInnerID].ToString();
                        string innerIDField = Manager.Properties.Select(Alias.Module.Object.Property.ObjectID + "='" + rows[0][Alias.Module.Object.ID] + "' and " + Alias.Module.Object.Property.Name + "='InnerID'")[0][Alias.Module.Object.Property.UniqueInnerID].ToString();
                        string nameField = Manager.Properties.Select(Alias.Module.Object.Property.ObjectID + "='" + rows[0][Alias.Module.Object.ID] + "' and " + Alias.Module.Object.Property.Name + "='Name'")[0][Alias.Module.Object.Property.UniqueInnerID].ToString();

                        IObject privilegeBll = null;
                        string roleNoField = null;
                        string subInstanceIDField = null;

                        Dictionary<string, string> kvs = new Dictionary<string, string>();
                        string subinstancesof = String.Empty;
                        foreach (DataRow subinstance in table.Rows)
                        {
                            #region 对该子实例，当前用户是子用户，则检查有没有任何权限，如果没有，不采纳
                            if (subinstance[userIDField].ToString() != user["ID"])
                            {
                                if (privilegeBll == null)
                                {
                                    DataRow userInstance = Manager.Instances.Select(Alias.Module.Namespace + "='AliCMS.UserModule'")[0];
                                    privilegeBll = Manager.CreateObject("Privilege", (int)userInstance[Alias.Instance.InnerID], PageLang, false);

                                    rows = Manager.Objects.Select(Alias.Module.Object.Namespace + "='AliCMS.UserModule' and " + Alias.Module.Object.Name + "='Privilege'");
                                    roleNoField = Manager.Properties.Select(Alias.Module.Object.Property.ObjectID + "='" + rows[0][Alias.Module.Object.ID] + "' and " + Alias.Module.Object.Property.Name + "='RoleNo'")[0][Alias.Module.Object.Property.UniqueInnerID].ToString();
                                    subInstanceIDField = Manager.Properties.Select(Alias.Module.Object.Property.ObjectID + "='" + rows[0][Alias.Module.Object.ID] + "' and " + Alias.Module.Object.Property.Name + "='SubInstanceID'")[0][Alias.Module.Object.Property.UniqueInnerID].ToString();
                                }

                                condition = null;
                                foreach (string subuser in subusers)
                                {
                                    string[] pair = subuser.Split(',');
                                    if (subinstance[userIDField].ToString() != pair[0])
                                        continue;

                                    if (condition != null)
                                        condition += " OR ";
                                    condition += "(" + roleNoField + "=" + pair[1] + " AND " + subInstanceIDField + "=" + subinstance[idField] + ")";
                                }

                                DataTable table2 = (DataTable)bll.GetType().InvokeMember("List", System.Reflection.BindingFlags.InvokeMethod, null, bll, new object[] { -1, -1, condition, null });
                                if (table2.Rows.Count == 0)
                                    continue;
                            }
                            #endregion

                            if (subinstancesof == String.Empty)
                            {
                                defaultSubInstanceInnerIDOf = subinstance[innerIDField].ToString();
                                kvs["DefaultSubInstanceIDOf" + InstanceID] = subinstance[idField].ToString();
                                kvs["DefaultSubInstanceInnerIDOf" + InstanceID] = subinstance[innerIDField].ToString();
                            }
                            else
                            {
                                subinstancesof += ";";
                            }
                            subinstancesof += subinstance[idField] + "|" + subinstance[innerIDField] + "|" + subinstance[nameField] + "|" + subinstance[userIDField];
                        }
                        kvs["SubInstancesOf" + InstanceID] = subinstancesof;
                        Manager.AddToUser(kvs);

                        subInstances = subinstancesof.Split(';');

                        if (privilegeBll != null)
                            privilegeBll.Dispose();
                    }
                    */
                }
                else
                {
                    defaultSubInstanceInnerIDOf = user["DefaultSubInstanceInnerIDOf" + InstanceID];
                    subInstances = user["SubInstancesOf" + InstanceID].Split(';');
                }
                #endregion

                DataTable result = new DataTable();
                result.Columns.Add("ID", typeof(string));
                result.Columns.Add("InnerID", typeof(string));
                result.Columns.Add("Name", typeof(string));
                result.Columns.Add("UserID", typeof(string));
                result.Columns.Add("IsDefault", typeof(bool));

                foreach (string subInstance in subInstances)
                {
                    string[] columns = subInstance.Split('|');

                    DataRow row = result.NewRow();
                    row["ID"] = columns[0];
                    row["InnerID"] = columns[1];
                    row["Name"] = columns[2];
                    row["UserID"] = columns[2];
                    if (columns[1] == defaultSubInstanceInnerIDOf)
                        row["IsDefault"] = true;
                    else
                        row["IsDefault"] = false;
                    result.Rows.Add(row);
                }

                return result;
            }
        }
        protected DataTable AllSubInstances
        {
            get
            {
                DataTable result = new DataTable();
                result.Columns.Add("InstanceID", typeof(Guid));
                result.Columns.Add("InstanceName", typeof(string));
                result.Columns.Add("Namespace", typeof(string));
                result.Columns.Add("SubInstanceID", typeof(Guid));
                result.Columns.Add("SubInstanceName", typeof(string));

                Dictionary<string, string> user = Manager.User;

                foreach (DataRow instance in Manager.Instances.Rows)
                {
                    bool isMultiUser = (bool)instance[Alias.Instance.IsMultiUser];
                    if (isMultiUser)
                    {
                        DataTable subinstances = getSubInstances((int)instance[Alias.Instance.InnerID], user, false);
                        foreach (DataRow subinstance in subinstances.Rows)
                        {
                            DataRow row = result.NewRow();
                            row["InstanceID"] = instance[Alias.Instance.ID];
                            row["InstanceName"] = instance[Alias.Instance.Name + PageLang];
                            row["Namespace"] = instance[Alias.Module.Namespace];
                            row["SubInstanceID"] = subinstance["ID"];
                            row["SubInstanceName"] = subinstance["Name"];
                            result.Rows.Add(row);
                        }
                    }
                }

                return result;
            }
        }
        #endregion

        #region Fields
        #endregion
    }
}
